// ui/access_control.go
package ui

import (
	"device_manager/api"
	"device_manager/config"
	"device_manager/utils"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
	"gorm.io/gorm"
)

func CreateAccessControlTab(db *gorm.DB, cfg *config.Config) fyne.CanvasObject {
	devices := loadDevices(db, "门禁")

	deviceList := widget.NewList(
		func() int { return len(devices) },
		func() fyne.CanvasObject {
			nameLabel := widget.NewLabel("")
			snLabel := widget.NewLabel("")
			openButton := widget.NewButton("开门", nil)
			logButton := widget.NewButton("查看日志", nil)
			row := container.NewHBox(
				nameLabel,
				snLabel,
				openButton,
				logButton,
			)
			return row
		},
		func(i widget.ListItemID, o fyne.CanvasObject) {
			row := o.(*fyne.Container)
			labels := row.Objects

			nameLabel := labels[0].(*widget.Label)
			snLabel := labels[1].(*widget.Label)
			openButton := labels[2].(*widget.Button)
			logButton := labels[3].(*widget.Button)

			device := devices[i]
			nameLabel.SetText(device.Name)
			snLabel.SetText(device.DeviceSN)

			openButton.OnTapped = func() {
				err := api.OpenDoor(&device, cfg)
				result := "成功"
				if err != nil {
					result = "失败：" + err.Error()
					utils.ShowError(err)
				} else {
					utils.ShowInfo("开门指令已发送")
				}
				logAction(db, device.ID, "开门", result)
			}

			logButton.OnTapped = func() {
				showDeviceLogs(db, &device)
			}
		},
	)

	addButton := widget.NewButton("刷新列表", func() {
		devices = loadDevices(db, "门禁")
		deviceList.Refresh()
	})

	header := container.NewHBox(
		widget.NewLabelWithStyle("设备名称", fyne.TextAlignLeading, fyne.TextStyle{Bold: true}),
		widget.NewLabelWithStyle("设备SN", fyne.TextAlignLeading, fyne.TextStyle{Bold: true}),
		widget.NewLabel(""),
		widget.NewLabel(""),
	)

	content := container.NewBorder(
		header,
		addButton,
		nil,
		nil,
		deviceList,
	)

	return content
}
